package com.xiaoliang.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * @author XIAOLIANG
 * @ClassName LoginFilter.java
 * @Description TODO
 * @createTime 2021年02月23日 14:14:00
 */
public class LoginFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


		HttpServletRequest req = (HttpServletRequest) servletRequest;

		HttpServletResponse resp  = (HttpServletResponse) servletResponse;

		HttpSession session = req.getSession();

		Object login = session.getAttribute("login");

		String path = req.getContextPath();

		String remoteHost = req.getRemoteHost();
//		System.out.println(remoteHost);
		StringBuffer requestURL = req.getRequestURL();
		Map<String, String[]> params = req.getParameterMap();
		String queryString = "";
		for (String key : params.keySet()) {
			String[] values = params.get(key);
			for (int i = 0; i < values.length; i++) {
				String value = values[i];
				queryString += key + "=" + value + "&";
			}
		}

		System.out.println("来自"+remoteHost+"主机的请求-请求地址:"+requestURL+"-请求参数:"+queryString);

		if (login!=null||path.contains("login") || path.contains("regist")||path.contains("register")){

			filterChain.doFilter(req,resp);

		}else if (login==null){
			System.out.println("未登录 跳转到登录页面");
			resp.sendRedirect(req.getContextPath()+"/login.html");
		}

	}

	@Override
	public void destroy() {

	}
}
